import React, { useState, useEffect } from 'react';
import { Modal, Tabs, message, Spin, Button } from 'antd';

import { useDispatch, useSelector } from 'react-redux';
import { setBackground, setWatermark } from '@/store/reducers/setting';
import Background from './Background';
import Watermark from './Watermark';

import { useTranslation } from 'react-i18next';
import UpoladFooter from './UpoladFooter';
import AgentServer, { IEvent } from '@/modules/Agent';
import Loading from '@/components/Loading';

import './styles/setting.less';
import styled from '@emotion/styled';
import DeviceConfigure from './DeviceConfigure';
import useSyncState from '../hooks/useSyncState';

interface BackgroundModalProps {
	visible?: boolean;
	onOK?: () => void;
	cancel?: () => void;
}

const BackgroundModal = (props: BackgroundModalProps) => {
	const { t } = useTranslation();
	const dispatch = useDispatch();

	const { configure, mediaStreamController, agentDao } = AgentServer;
	const { visible } = props;
	// const { configure, setting } = useSelector((state: RootState) => state);

	const [bgImageList, setBackgroundImageList] = useState(agentDao.getBackgroundList());
	const [watermarkImageList, setWatermarkImageList] = useState(agentDao.getWaterMarkList());

	const [backgroundID, setBackGroundID] = useState<number>(agentDao.getBackgroundId());
	const [watermarkID, setWatermarkID] = useState<number>(agentDao.getWaterMarkId());

	const [loading, setLoading] = useState<boolean>(false);

	const [selectKey, setSelectKey] = useState<string>('1');

	const [audioInput, setAudioInput] = useState<MediaDeviceInfo[]>(AgentServer.getAudioDevices());
	const [audioOutput, setAudioOutput] = useState<MediaDeviceInfo[]>(AgentServer.getSpeakerDevices());
	const [videoInput, setVideoInput] = useState<MediaDeviceInfo[]>(AgentServer.getVideoDevices());

	const [defaultAudioInput, setDefaultAudioInput] = useSyncState<MediaDeviceInfo | undefined>(undefined);

	const [defaultSperaker, setDefaultSperaker] = useSyncState<MediaDeviceInfo | undefined>(undefined);

	const [defaultVideoInput, setDefaultVideoInput] = useSyncState<MediaDeviceInfo | undefined>(undefined);

	const [devicesID, setDevicesID] = useState<{ videoID: string | undefined; audioID: string | undefined; speakerID: string | undefined }>({
		videoID: undefined,
		audioID: undefined,
		speakerID: undefined
	});

	const LoadingContainer = styled.div`
		position: fixed;
		top: 0;
		left: 0;
		background: rgba(0, 0, 0, 0.52);
		z-index: 9000;
		width: 100vw;
		height: 100vh;
	`;

	const UploadTips = styled.div`
		width: 140px;
		height: 160px;
		background-color: #fff;
		border-radius: 10px;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		text-align: center;
		line-height: 90px;
		.widget-loading-container {
			padding-top: 40px;
			text-align: center;
			.sk-fading-circle {
				margin: 0 auto;
			}
		}
	`;

	useEffect(() => {
		AgentServer.addEventListener(resp => {
			if (resp.event === IEvent.BACKGROUND) {
				setBackgroundImageList(agentDao.getBackgroundList());
			}
			if (resp.event === IEvent.WATERMARK) {
				setWatermarkImageList(agentDao.getWaterMarkList());
			}
		});

		AgentServer.addDeviceEventLinstener(async (target: { event: string; type: string; device: MediaDeviceInfo }) => {
			if (target.event === 'deviceChange') {
				setAudioInput(AgentServer.getAudioDevices());
				setAudioOutput(AgentServer.getSpeakerDevices());
				setVideoInput(AgentServer.getVideoDevices());

				console.log('addDeviceEventLinstener:', AgentServer.getVideoDevices());

				setDefaultAudioInput(AgentServer.getAudioDevices().find(item => item.deviceId === AgentServer.getAudioDeviceID()));
				setDefaultSperaker(AgentServer.getSpeakerDevices().find(item => item.deviceId === AgentServer.getSpeakerDeviceID()));
				setDefaultVideoInput(AgentServer.getVideoDevices().find(item => item.deviceId === AgentServer.getVideoDeviceID()));
			}
		});

		return () => {
			AgentServer.removeEventListener();
			AgentServer.removeDeviceEventListener();
		};
	}, []);

	useEffect(() => {
		if (visible) {
			getBackgroundList();
			getMediaDeviceList();
		}
	}, [visible]);

	const getMediaDeviceList = async () => {
		await AgentServer.getUserMediaDevices();
		setAudioInput(AgentServer.getAudioDevices());
		setAudioOutput(AgentServer.getSpeakerDevices());
		setVideoInput(AgentServer.getVideoDevices());

		setDefaultAudioInput(AgentServer.getAudioDevices().find(item => item.deviceId === AgentServer.getAudioDeviceID()));
		setDefaultSperaker(AgentServer.getSpeakerDevices().find(item => item.deviceId === AgentServer.getSpeakerDeviceID()));
		setDefaultVideoInput(AgentServer.getVideoDevices().find(item => item.deviceId === AgentServer.getVideoDeviceID()));
	};

	const getBackgroundList = async () => {
		await AgentServer.getBackgroundList();
		setBackGroundID(agentDao.getBackgroundId());
		setBackgroundImageList(agentDao.getBackgroundList());
		// console.log(configure.backgroundImageList);
	};

	const getWaterMarkList = async () => {
		await AgentServer.initWaterMark();
		setWatermarkID(agentDao.getWaterMarkId());
		setWatermarkImageList(agentDao.getWaterMarkList());
	};

	const onBackgroundSelect = (id: number) => {
		setBackGroundID(id);
		console.log(id);
	};

	const onWatermarkSelect = (id: number) => {
		setWatermarkID(id);
	};

	const onChange = async (key: string) => {
		setSelectKey(key);

		if (key === '1' || key === '2' || key === '3') {
			getMediaDeviceList();
		}

		if (key === '4') {
			getBackgroundList();
		}
		if (key === '5') {
			getWaterMarkList();
		}
	};

	const handleOk = async () => {
		// 背景设置
		if (selectKey === '4') {
			agentDao.setBackgroundId(backgroundID);
			await AgentServer.applyBackground();
		}
		if (selectKey === '5') {
			agentDao.setWaterMarkId(watermarkID);
			await AgentServer.applyWaterMark(watermarkID);
		}

		// 呼叫设备设置
		if (devicesID.audioID !== 'default' && devicesID.audioID) {
			AgentServer.setAudioInputDeviceId(devicesID.audioID);
		} else if (devicesID.audioID === 'default') {
			AgentServer.setAudioInputDeviceId(undefined);
		}

		if (devicesID.videoID !== 'default' && devicesID.videoID) {
			AgentServer.setVideoInputDeviceId(devicesID.videoID);
		} else if (devicesID.videoID === 'default') {
			AgentServer.setVideoInputDeviceId(undefined);
		}
		if (devicesID.speakerID !== 'default' && devicesID.speakerID) {
			AgentServer.setAudioOutputDeviceId(devicesID.speakerID);
		} else if (devicesID.speakerID === 'default') {
			AgentServer.setAudioOutputDeviceId(undefined);
		}

		props.onOK && props.onOK();
		message.info(t('virtaul-background-setting-success'));
	};

	const handleCancel = () => {
		props.cancel && props.cancel();
	};

	const deleteBackground = async (id: number) => {
		try {
			if (selectKey === '4') {
				await AgentServer.deleteBackground(id);
			} else {
				await AgentServer.delWaterMark(id);
			}
		} catch (error) {
			console.log(error);
		}
	};

	const brforeUpload = async (file: any) => {
		setLoading(true);
		try {
			if (selectKey === '4') {
				const data = await AgentServer.uploadBackground(file);
				console.log(data);
			} else {
				const data = await AgentServer.uploadWaterMark(file);
				console.log(data);
			}
		} catch (error) {
			console.log(error);
		} finally {
			setLoading(false);
		}
	};

	const onDeviceSelect = (data: { mode: 'video' | 'audio' | 'speaker'; id: string | undefined }) => {
		if (data.mode === 'audio') {
			setDevicesID({ ...devicesID, audioID: data.id });
		}
		if (data.mode === 'video') {
			setDevicesID({ ...devicesID, videoID: data.id });
		}
		if (data.mode === 'speaker') {
			setDevicesID({ ...devicesID, speakerID: data.id });
		}
	};

	const getFooter = (key: string) => {
		if (key === '1' || key === '2' || key === '3') return null;
		if (key === '4' || key === '5') return <UpoladFooter cancel={handleCancel} submit={handleOk} beforeUpload={file => brforeUpload(file)} />;
	};

	const tabs = [
		{
			label: t('video-configure'),
			key: '1',
			children: (
				<DeviceConfigure
					onOk={handleOk}
					onCancel={handleCancel}
					onSelect={onDeviceSelect}
					defaultDevice={defaultVideoInput()}
					audioInput={audioInput}
					audioOutput={audioOutput}
					videoInput={videoInput}
					mode={'video'}
					selectKey={selectKey}
				/>
			)
		},
		{
			label: t('audio-configure'),
			key: '2',
			children: (
				<DeviceConfigure
					onOk={handleOk}
					onCancel={handleCancel}
					onSelect={onDeviceSelect}
					defaultDevice={defaultAudioInput()}
					audioInput={audioInput}
					audioOutput={audioOutput}
					videoInput={videoInput}
					mode={'audio'}
					selectKey={selectKey}
				/>
			)
		},
		{
			label: t('speaker-configure'),
			key: '3',
			children: (
				<DeviceConfigure
					onOk={handleOk}
					onCancel={handleCancel}
					onSelect={onDeviceSelect}
					defaultDevice={defaultSperaker()}
					audioInput={audioInput}
					audioOutput={audioOutput}
					videoInput={videoInput}
					mode={'speaker'}
					selectKey={selectKey}
				/>
			)
		},
		{
			label: t('virtaul-background'),
			key: '4',
			children: <Background deleteBackground={deleteBackground} selectedID={backgroundID} imageList={bgImageList} onSelect={onBackgroundSelect} />
		},
		{
			label: t('water-mark'),
			key: '5',
			children: <Watermark deleteBackground={deleteBackground} selectedID={watermarkID} imageList={watermarkImageList} onSelect={onWatermarkSelect} />
		}
	];

	const getItems = () => {
		let items = [...tabs];
		if (configure.preferenceSettings.watermarkConfigHidden) {
			// remove key 5
			items = items.filter(item => item.key !== '5');
		}
		if (configure.preferenceSettings.virtualBackgroundConfigHidden) {
			// remove key 4
			items = items.filter(item => item.key !== '4');
		}
		return items
	}

	return (
		<Modal
			wrapClassName="background-setting-modal"
			maskClosable={false}
			title={t('virtaul-background-setting')}
			width={573}
			open={visible}
			destroyOnClose={true}
			onOk={handleOk}
			onCancel={handleCancel}
			okText={t('sure')}
			cancelText={t('cancel')}
			footer={getFooter(selectKey)}
		>
			{loading ? (
				<LoadingContainer>
					<UploadTips>
						<Loading></Loading>
						正在上传中
					</UploadTips>
				</LoadingContainer>
			) : null}

			<Tabs
				defaultActiveKey={selectKey}
				onChange={onChange}
				items={ getItems()}
			/>
		</Modal>
	);
};

export default BackgroundModal;
